import { isNumLike } from '../../../utils/dataType.js';

export const loadPlugin = (plugin) => {
  plugin = String(plugin).replace(/^AMap\./, '');
  if (AMap[plugin]) {
    return Promise.resolve(AMap[plugin]);
  }
  return new Promise((resolve) => {
    AMap.plugin(`AMap.${plugin}`, () => resolve(AMap[plugin]));
  });
};

export const loadPlugins = (plugins) => {
  return Promise.all(plugins.map((plugin) => loadPlugin(plugin)));
};

export const getPlugins = function (plugin, args) {
  plugin = String(plugin).replace(/^AMap\./, '');
  function initPlugin(plugin, args) {
    args = Array.isArray(args) ? args : [args];
    return new AMap[plugin](...args);
  }
  if (AMap[plugin]) {
    return Promise.resolve(initPlugin(plugin, args));
  }
  return new Promise((resolve) => {
    AMap.plugin(`AMap.${plugin}`, () => resolve(initPlugin(plugin, args)));
  });
};

export const getLngLat = function (data) {
  if (!data) return;
  if (typeof data.getPosition === 'function') {
    data = data.getPosition();
  }
  if (typeof data === 'object') {
    if (data.lng && data.lat) {
      data = [data.lng, data.lat];
    } else if (data.longitude && data.latitude) {
      data = [data.longitude, data.latitude];
    }
  } else if (Array.isArray(data) && data[0] && data[1]) {
    data = [data[0], data[1]];
  } else if (typeof data === 'string' && data.indexOf(',') >= 0) {
    const [lng, lat] = data.split(',');
    data = [lng, lat];
  }
  try {
    const [lng, lat] = data;
    if (isNumLike(lng) && isNumLike(lat)) {
      data = new AMap.LngLat(...data);
    }
  } catch (e) {
    return;
  }
  if (data instanceof AMap.LngLat) {
    return data;
  }
};

export const isSameLngLat = (lngLat1, lngLat2) => {
  const p1 = getLngLat(lngLat1);
  const p2 = getLngLat(lngLat2);
  return p1 && p2 && p1.lng === p2.lng && p1.lat === p2.lat;
};
